package em.program.imp;

import base.util.DateUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import em.model.Warning;
import em.util.CommonTools;
import em.util.ConstUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by Administrator on 2016-1-30.
 * 实时工况处理
 */
public class RealData extends MsgApiImp {
    private Log logger = LogFactory.getLog(RealData.class);
    private Map<String,ArrayList<String>> saveMap=new ConcurrentHashMap<>();
    private Map<String,JSONArray> returnMap=new ConcurrentHashMap<String,JSONArray>();
    private static RealData realData=new RealData();
    private Thread thread ,thread1;

    public synchronized static RealData getInstance(){
        if (realData.thread == null) {
            realData.thread=new Thread(new Runnable() {
                @Override
                public void run() {
                    realData.jxData();
                }
            });
            realData.thread.start();
        }

        if (realData.thread1 == null) {
            realData.thread1=new Thread(new Runnable() {
                @Override
                public void run() {
                    realData.checkTime();
                }
            });
            realData.thread1.start();
        }
        return realData;
    }

    /**
     * 检查时间
     */
    private  void  checkTime(){
        JSONObject jsonObject;
        Iterator<Map.Entry<String, ArrayList<String>>> it;
        Map.Entry<String,ArrayList<String>> entry;

        while (true) {
            it = saveMap.entrySet().iterator();
            while (it.hasNext()){
                entry= it.next();
                if(entry.getValue().size()==0) {
                    if(getCurrentStatus(entry.getKey())==9)//如果是在刷工况,则将状态改掉
                        setCurrentStatus(entry.getKey(), 0);
                }
            }

            try {
                Thread.sleep(4000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 解析数据
     */

    private void jxData(){
        try {
            JSONObject jsonObject;
            JSONArray jsonArray=new JSONArray(),saveJsonArray=new JSONArray();
            String strTTIME, strDITTO, k, str,strTermCode;
            boolean isWarning=false;
            ArrayList<String> v;
            ArrayList<Warning> saveList=new ArrayList<>();
            Date dateTime;
            //取得最后的一条数据
            while (true) {
                for (Map.Entry<String, ArrayList<String>> entry : saveMap.entrySet()) {
                    k = entry.getKey();
                    v = entry.getValue();
                    if (v.size() > 0) {
                        jsonArray.clear();

                        if (!returnMap.containsKey(k)) {
                            returnMap.put(k, new JSONArray());
                        }
                        str = v.get(0);
                        jsonObject = JSONObject.parseObject(str);

                        //采集时间
                        strTTIME = jsonObject.getString("TTIME");
                        dateTime = DateUtil.getInstance().getDateLong(strTTIME.substring(0, 4) + "-" + strTTIME.substring(4, 6) + "-" + strTTIME.substring(6, 8) + " " + strTTIME.substring(8, 10) + ":" + strTTIME.substring(10, 12) + ":" + strTTIME.substring(12, 14));



                        //数据内容
                        jxDetail(jsonObject.getString("CONDITION"));

//                        System.out.println("原始数据:"+str);
//                        System.out.println("解析后的数据:"+jsonArray.toJSONString());
                        System.out.println("-----------------------------------------------------------------------");
//                        //如果报警,则保存数据
//                        if(isWarning){
//                            saveList.clear();
//                            saveJsonArray=returnMap.get(k);
//                            Long group=DateUtil.getInstance().getCurrentTime();
//                            strTermCode="PT"+(Integer.valueOf(k) ^ 0x5A5A5A5A);
//
//                            //添加报警
//                            Warning warning = new Warning();
//                            warning.set("group", group).set("term_code", strTermCode).set("get_date",DateUtil.getInstance().getString(dateTime)).set("jx_data",jsonArray.toJSONString()).set("content",str).set("is_flag",1);
//                            saveList.add(CommonTools.getInstance().copyObject(warning));
//                            for (int i=0;i<saveJsonArray.size()-1;i++) {
//                                warning.clear();
//                                warning.set("group", group).set("term_code", strTermCode).set("get_date",saveJsonArray.getJSONObject(i).getString("date")).set("jx_data",jsonArray.toJSONString()).set("content",saveJsonArray.getJSONObject(i).getString("content")).set("is_flag",0);
//                                saveList.add(CommonTools.getInstance().copyObject(warning));
//                            }
//
//                            //保存数据
//                            //Db.batchSave(saveList,saveList.size());
//                        }

                        if (jsonObject.containsKey("DITTO")) {
                            strDITTO = jsonObject.getString("DITTO");
                            for (int i = 0; i < strDITTO.length(); i++) {
                                JSONObject jsonObject1 = new JSONObject();
                                jsonObject1.put("date", DateUtil.getInstance().getString(DateUtil.getInstance().addSecond(dateTime, Integer.parseInt(strDITTO.substring(i, i + 1)))));
                                jsonObject1.put("list", CommonTools.getInstance().copyObject(jsonArray));
                                jsonObject1.put("content",str);
                                returnMap.get(k).add(0, jsonObject1);

                                //每个设备只存放50条数据
                                if (returnMap.get(k).size() > 50) {
                                    returnMap.get(k).remove(returnMap.get(k).size() - 1);
                                }
                            }
                        } else {
                            JSONObject jsonObject1 = new JSONObject();
                            jsonObject1.put("date", DateUtil.getInstance().getString(dateTime));
                            jsonObject1.put("list", CommonTools.getInstance().copyObject(jsonArray));
                            jsonObject1.put("content",str);
                            returnMap.get(k).add(0, jsonObject1);

                            //每个设备只存放50条数据
                            if (returnMap.get(k).size() > 50) {
                                returnMap.get(k).remove(returnMap.get(k).size() - 1);
                            }
                        }

                        saveMap.get(k).remove(str);//移走
                    }
                }

                //暂定100毫秒
                Thread.sleep(100);
            }
        }catch (Exception ex){
            System.out.println(ex.getMessage());
        }
    }

    /**
     * 解析plc数据
     * @param jxStr
     * @return
     */
    private JSONObject jxDetail(String jxStr){
        int i=0;
        JSONObject jsonObject=new JSONObject();
        String strTemp;
        if(jxStr.length()>=144){
            //前面36个字节
            for(i=0;i<36;i++) {
                jsonObject=new JSONObject();

                if(i==34 || i==35){
                    strTemp= CommonTools.getInstance().hexTo10Scale(jxStr.substring((i * 2), (i + 1) * 2));
                    jsonObject.put("VB"+(3000+i),strTemp.split(","));//34主起升电机温度,35副起升电机温度
                }else{
                    strTemp= CommonTools.getInstance().hexTo2Scale(jxStr.substring((i * 2), (i + 1) * 2));
                    jsonObject.put("VB"+(3000+i),strTemp.split(","));
                }
            }

            //后面的
            for(i=36;i<72;i=i+2){
                jsonObject=new JSONObject();
                strTemp= CommonTools.getInstance().hexTo10Scale(jxStr.substring(i * 2, i * 2+4));
                jsonObject.put("VW"+(3000+i),strTemp.split(","));
            }
        }
        return jsonObject;
    }
    /**
     * 终端返回的数据
     * @param jsonObject
     */
    protected void setData(JSONObject jsonObject){
        if(!saveMap.containsKey(jsonObject.getString("TNUM"))){
            saveMap.put(jsonObject.getString("TNUM"), new ArrayList<String>());
        }

        saveMap.get(jsonObject.getString("TNUM")).add(jsonObject.toString());
    }

    /**
     * 取得数据
     * @param strTnum 终端号
     * @param strInterval 终端上传数据的间隔
     * @return
     */
    public String getData(String strTnum,int strInterval){
        //发送工况命令
        //判断是否需要发送命令
        Integer iStatus= isCheckStatus(strTnum,9);
        if(iStatus!=0 && iStatus!=-2){
            return String.format(ConstUtil.ERROR_ACTION,iStatus);
        }

        if(iStatus==0){
            sendData(String.format(ConstUtil.ACTION_10_R,strTnum,strInterval));//发送指令
            setCurrentStatus(strTnum,9);
        }

//       // 取得数据
//        return getResultData(strTnum,saveMap,60,false);
        return "{\"VB3000\":[\"0\",\"1\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\"],\"VB3001\":[\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\"],\"VB3002\":[\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\"],\"VB3003\":[\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\"],\"VB3004\":[\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\"],\"VB3005\":[\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\"],\"VB3006\":[\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\"],\"VB3007\":[\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\"],\"VB3008\":[\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\"],\"VB3009\":[\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\"],\"VB3010\":[\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\"],\"VB3011\":[\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\"],\"VB3012\":[\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\"],\"VB3013\":[\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\"],\"VB3014\":[\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\"],\"VB3015\":[\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\"],\"VB3016\":[\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\"],\"VB017\":[\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\"],\"VB3018\":[\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\"],\"VB3019\":[\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\"],\"VB3020\":[\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\"],\"VB3021\":[\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\"],\"VB3022\":[\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\"],\"VB3023\":[\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\"],\"VB3024\":[\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\"],\"VB3025\":[\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\"],\"VB3026\":[\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\"],\"VB3027\":[\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\"],\"VB3028\":[\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\"],\"VB3029\":[\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\"],\"VB3030\":[\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\"],\"VB3031\":[\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\"],\"VB3032\":[\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\"],\"VB3033\":[\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\"],\"VB3034\":[\"0\"],\"VB3035\":[\"0\"],\"VW3036\":[\"0\"],\"VW3038\":[\"0\"],\"VW3040\":[\"0\"],\"VW3042\":[\"0\"],\"VW3044\":[\"0\"],\"VW3046\":[\"0\"],\"VW3048\":[\"0\"],\"VW3050\":[\"0\"],\"VW3052\":[\"0\"],\"VW3054\":[\"0\"],\"Time\":\"12:30:30\"}";
    }

    /**
     * 停止实时工况
     */
    public void stopRealAction(String strTnum){
        if(getCurrentStatus(strTnum)==9){
            sendData(String.format(ConstUtil.ACTION_10_R,strTnum,"0"));//发送指令
            setCurrentStatus(strTnum,0);
        }
    }

}
